<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
        <li><a href="/home">首页</a></li>
        <li><a href="/list">列表</a></li>
    </ul>
     <!-- 当rul变更后，展示对应的代码片段 -->
    <div id="root"></div>

    <script>
        const router=[
        {
            path:'/home',
            component:()=>{
                return `<h1>首页页面</h1>`
            }
        },
        {
            path:'/list',
            component:()=>{
                return `<h1>列表页面</h1>`
            }
        }
      ]  
      let routerView=document.getElementById('root')
      
      window.addEventListener('DOMContentLoaded',()=>{
         onLoad()
      })
      function onLoad(){
        let lingList=document.querySelectorAll('a[href]')
        lingList.forEach(el=>{
            el.addEventListener('click',(e)=>{
                e.preventDefault()//阻止默认行为 
                history.pushState(null,'',el.getAttribute('href'))//进入浏览器的缓存栈     但不受前进后退事件的影响           
            })
        })
      }
      window.addEventListener('popstate',()=>{//监听浏览器的前进后退事件
        renderView(location.pathname)
      })
      
      
      function renderView(url){
        let index=router.findIndex(item=>{
            return item.path===url
        })
        routerView.innerHTML=router[index].component()
      }






    </script>
</body>
</html>